package com.tjp.subject.application.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @program: jz-club
 * @description: 功能是配置一个全局的JSON消息转换器，用于处理控制器方法的JSON格式的输入和输出数据
 * @author: aaronTang
 * @create: 2024-03-02
 */
@Configuration
public class GlobalConfig extends WebMvcConfigurationSupport {
    //继承WebMvcConfigurationSupport 表名它是一个Web MVC配置类 用于SpringMVC


    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        //将一个自定义的Jackson Json消息转换器添加到转换器列表中  Jackson是一个流行的Java JSON库
        converters.add(mappingJackson2HttpMessageConverter());
    }

    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        //ObjectMapper是Jackson库的主类,用于执行Json的序列化和反序列化操作
        ObjectMapper objectMapper = new ObjectMapper();
        //设置当对象为空时不抛出异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //隐藏实体类中值为空的属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //将objectMapper对象传递,用于配置JSON消息转换器
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);

        return converter;

    }
}
